package cn.sjlink.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author tiny
 * @date 2019/12/11 17:14
 * @description
 */
public class JedisUtil {
    private JedisPool pool = null;
    private JedisUtil(){
        if (pool == null) {
            String ip = ConfigUtil.get("aliRedisHost");
            int port = Integer.parseInt(ConfigUtil.get("aliRedisPort"));
            String password = ConfigUtil.get("aliRedisPassword");
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(8);
            jedisPoolConfig.setMaxIdle(0);
            jedisPoolConfig.setMaxWaitMillis(3000);
            if (password != null && !"".equals(password)) {
                // redis 设置了密码
                pool = new JedisPool(jedisPoolConfig, ip, port, 10000, password);
            } else {
                // redis 未设置密码
                pool = new JedisPool(jedisPoolConfig, ip, port, 10000);
            }
        }
    }
    private Jedis getJedis() {
        Jedis resource = pool.getResource();
        resource.select(6);
        return resource;
    }

    public static JedisUtil getRedisUtil() {
        return new JedisUtil();
    }
    /**
     * @param key
     * @return
     */
    public String setex(String key, int seconds, String value) {
        Jedis jedis = getJedis();
        return jedis.setex(key, seconds, value);
    }
    public String getKey(String key){
        Jedis jedis = getJedis();
        return jedis.get(key);
    }
    public Long getTtl(String key){
        Jedis jedis = getJedis();
        return jedis.ttl(key);
    }
    public void remove(String key){
        Jedis jedis = getJedis();
        Long del = jedis.del(key);
    }
}
